/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Backend;

/**
 *
 * @author insane
 */
import Backend.models.ItemTableModel;
import Backend.models.MapTableModel;
import IO.models.ItemsConfig;
import IO.models.MapsConfig;
import Items.Item;
import Map.Map;
import java.awt.AWTException;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.TextField;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

/**
 *
 * @author insane
 */
public class Form extends JDialog implements ListSelectionListener, ActionListener {

    private TrayIcon trayIcon;
    private SystemTray systemTray = SystemTray.getSystemTray();
    private JTabbedPane tabbedPane;
    private JPanel map;
    private JPanel weapon;
    private JPanel monsters;
    private JTable mapTable;
    private TextField mapWidth;
    private TextField mapHeight;
    private TextField mapLevel;
    private TextField mapDensity;
    private TextField mapObjHeight;
    private TextField mapObjWidth;
    private JPanel editMap;
    private MapTableModel mapModel;
    private JButton addMap;
    private TableRowSorter<TableModel> sorter;
    private JPanel gameplay;
    private JPanel item;
    private ItemTableModel itemModel;
    private JTable itemTable;
    private TableRowSorter itemsorter;
    private JPanel editItem;
    private TextField itemWidth;
    private TextField itemHeight;
    private TextField itemLevel;
    private TextField itemDensity;
    private TextField itemObjHeight;
    private TextField itemObjWidth;
    private JButton addItem;
    private TextField itemSee;
    private TextField itemAction;
    private TextField itemName;
    private TextField itemDrop;
    private TextField itemCount;
    private JButton delItem;

    Form() throws IOException, AWTException, FileNotFoundException, ClassNotFoundException {

        setTitle("backend");

        getContentPane().setLayout(new BorderLayout());

        seeIcon();

        initComponents();

        Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
        setBounds(0, 20, 500, 550);
    }

    private void initMapComponents() throws FileNotFoundException, IOException, ClassNotFoundException {
        /*
         * map table
         */
        mapModel = new MapTableModel(MapsConfig.getInstance().getMap());
        mapTable = new JTable(mapModel);
        mapTable.getSelectionModel().addListSelectionListener(this);
        sorter = new TableRowSorter(mapModel);
        sorter.toggleSortOrder(0);
        mapTable.setRowSorter(sorter);


        map.setLayout(new BorderLayout());
        editMap = new JPanel();
        editMap.setLayout(
                new BoxLayout(editMap, BoxLayout.X_AXIS));
        map.add(editMap, BorderLayout.NORTH);
        map.add(new JScrollPane(mapTable), BorderLayout.SOUTH);

        mapWidth = new TextField();
        mapHeight = new TextField();
        mapLevel = new TextField();
        mapDensity = new TextField();
        mapObjHeight = new TextField();
        mapObjWidth = new TextField();

        editMap.add(mapLevel);
        editMap.add(mapWidth);
        editMap.add(mapHeight);
        editMap.add(mapDensity);
        editMap.add(mapObjWidth);
        editMap.add(mapObjHeight);
        addMap = new JButton("Добавить");
        addMap.addActionListener(this);
        editMap.add(addMap);
    }

    private void initItemsComponents() throws FileNotFoundException, IOException, ClassNotFoundException {
        /*
         * map table
         */
        itemModel = new ItemTableModel(ItemsConfig.getInstance().getItems());
        itemTable = new JTable(itemModel);
        itemTable.getSelectionModel().addListSelectionListener(this);
        itemsorter = new TableRowSorter(itemModel);
        itemsorter.toggleSortOrder(0);
        itemTable.setRowSorter(itemsorter);

        JPanel editButton = new JPanel();

        item.setLayout(new BorderLayout());
        editItem = new JPanel();
        editItem.setLayout(
                new BoxLayout(editItem, BoxLayout.X_AXIS));
        item.add(editItem, BorderLayout.NORTH);
        item.add(editButton, BorderLayout.CENTER);
        item.add(new JScrollPane(itemTable), BorderLayout.SOUTH);

        itemSee = new TextField();
        itemAction = new TextField();
        itemName = new TextField();
        itemDrop = new TextField();
        itemLevel = new TextField();
        itemCount = new TextField();

        editItem.add(itemSee);
        editItem.add(itemName);
        editItem.add(itemAction);
        editItem.add(itemDrop);
        editItem.add(itemLevel);
        editItem.add(itemCount);

        delItem = new JButton("Удалить");
        delItem.addActionListener(this);
        editButton.add(delItem);
        addItem = new JButton("Добавить");
        addItem.addActionListener(this);
        editButton.add(addItem);
    }

    private void initComponents() throws FileNotFoundException, IOException, ClassNotFoundException {

        map = new JPanel();
        item = new JPanel();
        weapon = new JPanel();
        monsters = new JPanel();
        gameplay = new JPanel();

        initMapComponents();
        initItemsComponents();

        tabbedPane = new JTabbedPane();
        tabbedPane.addTab("Уровни", map);
        tabbedPane.addTab("Предметы", item);
        tabbedPane.addTab("Оружие", weapon);
        tabbedPane.addTab("Монстры", monsters);
        tabbedPane.addTab("Игра", gameplay);

        getContentPane().add(tabbedPane, BorderLayout.CENTER);

    }

    private void seeIcon() throws IOException, AWTException {
//popup for icon
        PopupMenu popupMenu = new PopupMenu();
        //PopupMenu popupNewMenu = new PopupMenu();
        MenuItem popupExit = new MenuItem("Exit");
        //popupMenu.add(popupExit);
        popupMenu.add(popupExit);
        //Icon
        trayIcon = new TrayIcon(ImageIO.read(getClass().getResource("ico.gif")), "fuck..");
        trayIcon.setImageAutoSize(true);
        trayIcon.setPopupMenu(popupMenu);
        systemTray.add(trayIcon);
        //Icon view listers
        trayIcon.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                setVisible(true);
            }
        });
        trayIcon.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                if (!isVisible()) {
                    setVisible(true);
                }
            }
        });
        //Listers Icon popup
        popupExit.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                dispose();
                System.exit(0);
            }
        });
    }

    public static void main(String args[]) throws IOException, AWTException, FileNotFoundException, ClassNotFoundException {
        Form vf = new Form();
        vf.setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource().equals(delItem)) {
            try {
                ItemsConfig.getInstance().getItems().remove(itemTable.convertRowIndexToModel(itemTable.getSelectedRow()));
                itemModelReload();
            } catch (FileNotFoundException ex) {
                Logger.getLogger(Form.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(Form.class.getName()).log(Level.SEVERE, null, ex);
            } catch (ClassNotFoundException ex) {
                Logger.getLogger(Form.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        if (e.getSource().equals(addItem)) {
            try {
                Item item = new Item(itemSee.getText().charAt(0), itemName.getText(), itemAction.getText(), Double.parseDouble(itemDrop.getText()), Integer.parseInt(itemCount.getText()));

                if (!itemLevel.getText().isEmpty()) {
                    if (itemModel.isExist(itemSee.getText()) == -1) {

                        ItemsConfig.getInstance().getItems().add(item);
                    } else {
                        ItemsConfig.getInstance().getItems().set(itemModel.isExist(itemSee.getText()), item);
                    }

                    itemModelReload();
                    ItemsConfig.getInstance().save();
                }

            } catch (FileNotFoundException ex) {
                Logger.getLogger(Form.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(Form.class.getName()).log(Level.SEVERE, null, ex);
            } catch (ClassNotFoundException ex) {
                Logger.getLogger(Form.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        if (e.getSource().equals(addMap)) {
            if (!mapLevel.getText().isEmpty()
                    && !mapWidth.getText().isEmpty()
                    && !mapHeight.getText().isEmpty()
                    && !mapDensity.getText().isEmpty()
                    && !mapObjWidth.getText().isEmpty()
                    && !mapObjHeight.getText().isEmpty()) {
                try {
                    if (mapModel.isExist(Integer.parseInt(mapLevel.getText())) != -1) {
                        MapsConfig.getInstance().getMap().set(mapModel.isExist(Integer.parseInt(mapLevel.getText())), new Map(Integer.parseInt(mapLevel.getText()), Integer.parseInt(mapWidth.getText()), Integer.parseInt(mapHeight.getText()), Double.parseDouble(mapDensity.getText()), Integer.parseInt(mapObjWidth.getText()), Integer.parseInt(mapObjHeight.getText())));
                    } else {
                        MapsConfig.getInstance().getMap().add(new Map(Integer.parseInt(mapLevel.getText()), Integer.parseInt(mapWidth.getText()), Integer.parseInt(mapHeight.getText()), Double.parseDouble(mapDensity.getText()), Integer.parseInt(mapObjWidth.getText()), Integer.parseInt(mapObjHeight.getText())));
                    }
                    mapLevel.setText("");
                    mapWidth.setText("");
                    mapHeight.setText("");
                    mapDensity.setText("");
                    mapObjWidth.setText("");
                    mapObjHeight.setText("");
                    mapModelReload();
                    MapsConfig.getInstance().save();
                } catch (FileNotFoundException ex) {
                    Logger.getLogger(Form.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IOException ex) {
                    Logger.getLogger(Form.class.getName()).log(Level.SEVERE, null, ex);
                } catch (ClassNotFoundException ex) {
                    Logger.getLogger(Form.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }

    private void mapModelReload() throws FileNotFoundException, IOException, ClassNotFoundException {
        mapTable.setModel(new MapTableModel(MapsConfig.getInstance().getMap()));
        sorter.toggleSortOrder(0);
        mapTable.setRowSorter(sorter);

    }

    private void itemModelReload() throws FileNotFoundException, IOException, ClassNotFoundException {
        itemTable.setModel(new ItemTableModel(ItemsConfig.getInstance().getItems()));
        itemsorter.toggleSortOrder(0);
        mapTable.setRowSorter(itemsorter);

    }

    @Override
    public void valueChanged(ListSelectionEvent e) {

        // если событие было сгенерировано нашей таблицей
        if (e.getSource() == mapTable.getSelectionModel() && e.getFirstIndex() >= 0 && mapTable.getSelectedRow() != -1) {
            int modelRow = -1;
            int viewRow = mapTable.getSelectedRow();
            if (viewRow < 0) {
            } else {
                modelRow =
                        mapTable.convertRowIndexToModel(viewRow);
            }
            mapLevel.setText(mapModel.getValueAt(modelRow, 0) + "");
            mapWidth.setText(mapModel.getValueAt(modelRow, 1) + "");
            mapHeight.setText(mapModel.getValueAt(modelRow, 2) + "");
            mapDensity.setText(mapModel.getValueAt(modelRow, 3) + "");
            mapObjWidth.setText(mapModel.getValueAt(modelRow, 4) + "");
            mapObjHeight.setText(mapModel.getValueAt(modelRow, 5) + "");

        }
        if (e.getSource() == itemTable.getSelectionModel() && e.getFirstIndex() >= 0 && itemTable.getSelectedRow() != -1) {
            int modelRow = -1;
            int viewRow = itemTable.getSelectedRow();
            if (viewRow < 0) {
            } else {
                modelRow =
                        itemTable.convertRowIndexToModel(viewRow);
            }
            itemSee.setText(itemModel.getValueAt(modelRow, 0) + "");
            itemName.setText(itemModel.getValueAt(modelRow, 1) + "");
            itemDrop.setText(itemModel.getValueAt(modelRow, 3) + "");
            itemAction.setText(itemModel.getValueAt(modelRow, 2) + "");
            itemLevel.setText(itemModel.getValueAt(modelRow, 4) + "");
            itemCount.setText(itemModel.getValueAt(modelRow, 5) + "");
        }
    }
}
